#!/usr/bin/perl

# ./catstarter.pl -app MyApp
# ./catstarter.pl -json -jemplate -app MyApp -db 'dbi:Pg:dbname=hoge akihito passwd'

# Load DBIC Example )
#   my $user = $c->model('DBIC')->schema->resultset('User')->search({name=>'akihito'})->first;

use strict;
use warnings;
use Getopt::Long;
use IO::File;
use Template;

my $app      = '';
my $json     = '';
my $jemplate = '';
my $db       = '';

my $result = GetOptions ( "app=s"       => \$app,
                          "db=s"        => \$db,
                          "jemplate"    => \$jemplate,
                          "json"        => \$json);

if( $app ){
    system("catalyst.pl $app");
    system("./$app/script/".lc($app)."_create.pl view TT TT");
    system("./$app/script/".lc($app)."_create.pl view JSON JSON") if($json);
    system("./$app/script/".lc($app)."_create.pl view Jemplate Jemplate") if($jemplate);
    system("./$app/script/".lc($app)."_create.pl  model DBIC DBIC::Schema create=static") if($db);
    system("mkdir ./$app/root/jemplate ") if($jemplate);

    my ($db_name,$db_user,$db_passwd) = split(' ',$db);
    my $dbclass_name = $app.'DB';
    system( qq|perl -MDBIx::Class::Schema::Loader=make_schema_at,dump_to_dir:./$app/lib -e 'make_schema_at("$dbclass_name", { relationships => 1 }, [ "$db_name","$db_user","$db_passwd"])'|)
      if( $db_name && $db_user && $db_passwd );

    my $line;
    do {$line .= $_} while( <DATA> );

    my $template = Template->new();
    my $param = {
                    DB_OBJ_NAME  => $dbclass_name,
                    APP_NAME     => $app,
                    DB_NAME      => $db_name   || '',
                    DB_USER      => $db_user   || '',
                    DB_PASSWD    => $db_passwd || '',
                    JSON         => $json      || '',
                    JEMPLATE     => $jemplate  || '',
                };

     my $str;
     $template->process(\$line,$param,\$str) || die $template->error();

     my $file = "./$app/".lc($app).".yml";
     my $fh = new IO::File();
     $fh->open($file,'w') || die "canot open YAML";
     print $fh $str;
     $fh->close(); 
     print "--CreateYAML--\n$str\n";
}

__DATA__
name: [% APP_NAME %]
[% IF DB_NAME %]
'Model::DBIC':
  schema_class: [% DB_OBJ_NAME %]
  connect_info:
   - [% DB_NAME %]
   - [% DB_USER %]
   - [% DB_PASSWD %]
   - AutoCommit: 0
     RaiseError: 1
[% END %][% IF JSON %]
'View::JSON':
  allow_callback: 1
  expose_stash: json
[% END %][% IF JEMPLATE %]
'View::Jemplate':
  jemplate_dir: root/jemplate
  jemplate_ext: '.html'
[% END %]

